import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getSysName } from "./whiteList";
import { Message } from 'element-ui';
// import packVariable from "../utils/packVariable";

NProgress.configure({ showSpinner: false })

/* ******* 解决路由重复的报错问题 ******* */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routers = [    // 不需要验证权限的页面，相当于白名单
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录',
    },
    component: resolve => require(['@/views/login'], resolve)
  },
  {
    path: '/layout',
    name: 'layout',
    meta: {
      title: '页面',
    },
    component: resolve => require(['@/views/layout.vue'], resolve),
  }
]

const createRouter = () => new VueRouter({
  mode: "history",
  routes: routers
})

const router = createRouter();
let isLoadedMenu = false

router.beforeEach(async (to, from, next) => {
  store.state.AllRoutes.forEach(item => {
    if (item.Url == to.name) to.meta.title = item.Title;
  })
  // const documentTitle = packVariable[process.env.VUE_APP_COMPANY_NAME].DOCUMENT_TITLE;
  // document.title = to.meta.title ? `${documentTitle}-${to.meta.title}` : `${documentTitle}`;
  NProgress.start()
  store.commit('updateTabs', { to, type: 'add' });
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    if (to.path === '/login' || to.path === '/error') {
      next()
      NProgress.done()
    } else {
      try {
        if (isLoadedMenu && to.name === null) {
          isLoadedMenu = false
          next('/error')
        } else if (to.name === null && (getSysName(to.path) != getSysName(from.path))) {        // 路由切换并且是系统之间的切换
          await store.dispatch('actionsGetMenu', { systemName: getSysName(to.path), toRoute: to.path })
          isLoadedMenu = true
          next({ ...to })
        } else {
          isLoadedMenu = false
          next()
        }
      } catch (error) {
        isLoadedMenu = false;
        NProgress.done()
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      Message({
        message: '登录状态已失效，请重新登录',
        type: 'error',
        showClose: true,
      })
      next(`/login`);
    }
    NProgress.done()
  }
});

router.afterEach(() => {
  NProgress.done()
})

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

export default router